package com.caregiver.watch.business.care.service.strategy.impl;

import com.alibaba.fastjson2.JSON;
import com.caregiver.watch.business.care.dao.HealthAlertConfigDao;
import com.caregiver.watch.business.care.enums.HealthAlertTypeEnum;
import com.caregiver.watch.business.care.model.bo.AlertMessageBo;
import com.caregiver.watch.business.care.model.bo.TemperatureWarningConfig;
import com.caregiver.watch.business.care.model.po.HealthAlertConfig;
import com.caregiver.watch.business.care.service.UserAlertRecordService;
import com.caregiver.watch.business.care.service.strategy.AbstractHealthWarningStrategy;
import com.caregiver.watch.business.data.protobuf.AlarmInfo;
import com.caregiver.watch.business.user.model.po.UserCareRecipient;
import com.caregiver.watch.business.user.service.UserDeviceService;
import com.caregiver.watch.common.utils.number.IntegerUtils;
import com.caregiver.watch.common.utils.time.DateUtils;
import com.caregiver.watch.thirdparty.service.JPushService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.caregiver.watch.common.constant.NumberConstants.BIG_DECIMAL_TEN_THOUSAND;
import static com.caregiver.watch.common.constant.NumberConstants.ZERO;

/**
 * @Description: 体温预警策略
 * @Author 疆戟
 * @Date 2025/11/2 17:40
 * @Version 1.0
 */
@Component
@Slf4j
public class TemperatureWarningStrategy extends AbstractHealthWarningStrategy<List<AlarmInfo.TemperatureConf>> {

    public TemperatureWarningStrategy(UserDeviceService userDeviceService, HealthAlertConfigDao healthAlertConfigDao, UserAlertRecordService userAlertRecordService, JPushService jPushService) {
        super(userDeviceService, healthAlertConfigDao, userAlertRecordService, jPushService);
    }

    @Override
    public void handle(Long userId, String deviceUuId, List<AlarmInfo.TemperatureConf> data) {
        log.info("处理体温预警：{}", data);
        if (CollectionUtils.isEmpty(data)) {
            log.warn("未获取到体温数据");
            return;
        }
        HealthAlertConfig config = getConfig();
        if (Objects.isNull(config) || BooleanUtils.isNotTrue(config.getEnabled())) {
            log.warn("未配置体温预警");
            return;
        }
        String alertConfig = config.getAlertConfig();
        if (StringUtils.isBlank(alertConfig)) {
            log.warn("未配置体温预警");
            return;
        }
        // 获取被关照人
        UserCareRecipient userCareRecipient = queryContactDeviceDetail(userId, deviceUuId);
        if (Objects.isNull(userCareRecipient)) {
            log.warn("未查询到被关照人");
            return;
        }
        List<TemperatureWarningConfig> temperatureWarningConfigs = JSON.parseArray(alertConfig, TemperatureWarningConfig.class);
        if (CollectionUtils.isEmpty(temperatureWarningConfigs)) {
            log.warn("未配置体温预警");
            return;
        }
        AlarmInfo.TemperatureConf tempAlarm = data.get(ZERO);
        // 获取告警时间
        LocalDateTime alarmTime = DateUtils.convert2LocalDateTime(tempAlarm.getTimeStamp().getDateTime().getSeconds());
        log.info("temperature alarm time:{},temperature:{}", alarmTime, tempAlarm.getTemperature());
        int temperature = IntegerUtils.ofNullable(tempAlarm.getTemperature());
        if (temperature <= ZERO) {
            log.warn("体温异常:{}", temperature);
            return;
        }
        Optional<TemperatureWarningConfig> first = temperatureWarningConfigs.stream().filter(warningConfig -> {
            if (Objects.isNull(warningConfig.getMaxTemperature()) && Objects.isNull(warningConfig.getMinTemperature())) {
                return false;
            } else if (Objects.isNull(warningConfig.getMaxTemperature())) {
                return temperature < convertTemperature(warningConfig.getMinTemperature());
            } else if (Objects.isNull(warningConfig.getMinTemperature())) {
                return temperature > convertTemperature(warningConfig.getMaxTemperature());
            }
            return temperature > convertTemperature(warningConfig.getMinTemperature())
                    && temperature < convertTemperature(warningConfig.getMaxTemperature());
        }).findFirst();
        if (!first.isPresent()) {
            log.warn("未匹配到体温预警配置");
            return;
        }
        TemperatureWarningConfig warningConfig = first.get();
        AlertMessageBo alertMessage = AlertMessageBo.build(warningConfig.getWarningTitle(), String.valueOf(temperature), warningConfig.getThreshold(), warningConfig.getHandleSuggestions());
        // 发送告警
        Boolean sendPush = sendPush(userId, userCareRecipient.getRecipientId(), config.getAlertType(), alarmTime, alertMessage);
        if (BooleanUtils.isTrue(sendPush)) {
            // 记录告警
            saveAlertRecord(userId, userCareRecipient.getRecipientId(), config.getAlertType(), alarmTime, JSON.toJSONString(alertMessage));
        }
    }

    /**
     * 体温转换
     */
    private Integer convertTemperature(BigDecimal temperature) {
        return BIG_DECIMAL_TEN_THOUSAND.multiply(temperature).intValue();
    }

    @Override
    public HealthAlertTypeEnum getAlertType() {
        return HealthAlertTypeEnum.TEMPERATURE_WARNING;
    }
}
